import Database from "better-sqlite3";
let db;

// 初始化数据库
function database_init(dbPath) {
    if (!db) {
        console.log(`数据库初始化的路径: ${dbPath}`)
        db = new Database(dbPath, { verbose: (message, additionalArgs) => console.log(`执行SQL语句为: ${message}, 附加参数为: ${JSON.stringify(additionalArgs ? additionalArgs : [])}`) });
        console.log(`数据库初始化成功`);
    }
    return db;
}

// 插入数据
function insert_data(table_name, data) {
    if (!Array.isArray(data)) {
        data = [data];
    }
    const keys = Object.keys(data[0]);
    db.prepare(`INSERT INTO ${table_name} (${keys.join(', ')}) VALUES ${data.map(item => `(${keys.map(column => `'${item[column]}'`)})`).join(', ')}`).run();
}

// 删除数据
function delete_data(table_name, where) {
    db.prepare(`DELETE FROM ${table_name} ${where ? `WHERE ${where}` : ''}`).run();
}

// 修改数据
function update_data(table_name, data, where) {
    db.prepare(`UPDATE ${table_name} SET ${Object.keys(data).map(column => `${column} = @${column}`).join(', ')} ${where ? `WHERE ${where}` : ''}`).run(data);
}

// 查询数据
function query_data(table_name, where, columns = '*', others = '') {
    return db.prepare(`SELECT ${columns} FROM ${table_name} ${where ? `WHERE ${where}` : ''} ${others}`).all();
}

// 直接执行SQL语句
function exec_sql(sql) {
    return db.exec(sql);
}

// 事务内执行
function transaction(callback) {
    db.transaction(callback)();
}

export { database_init, insert_data, delete_data, update_data, query_data, exec_sql, transaction };